using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using XenoGears.Functional;
using XenoGears.Reflection;

namespace Jink.Core.Json.Values
{
    public class JsonObject : JsonValue
    {
        public JsonObject()
            : base(false)
        {
        }

        public JsonObject(IEnumerable<KeyValuePair<String, JsonValue>> properties)
            : base(properties)
        {
        }

        public JsonObject(IEnumerable<Tuple<String, JsonValue>> properties)
            : base(properties.ToDictionary(kvp => kvp.Item1, kvp => kvp.Item2))
        {
        }

        public JsonObject(Object properties)
            : this(properties.ToPropertyBag().Cast<String, JsonValue>())
        {
        }

        public override void BuildCompactString(TextWriter writer)
        {
            writer.Write(String.Format("{{{0}}}", this.Select(kvp =>
                String.Format("{0}:{1}", kvp.Key, kvp.Value.ToCompactString())).StringJoin(",")));
        }

        public override void BuildPrettyString(IndentedTextWriter writer)
        {
            writer.WriteLine();
            writer.WriteLine("{");
            writer.Indent++;

            this.ForEach(kvp =>
            {
                writer.WriteLine("{0} :", kvp.Key);
                (kvp.Value ?? new JsonExpression("null")).BuildPrettyString(writer);
                writer.WriteLine(",");
            });

            writer.Indent--;
            writer.Write("}");
        }
    }
}